package com.xunce.xcworkservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunce.xcworkservice.dao.MenusMapper;
import com.xunce.xcworkservice.entity.Menus;
import com.xunce.xcworkservice.service.MenusService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:  MenusServiceImpl  
 * @Author:     yanlong.guo      
 * @Date:       2023/12/28 16:21   
 */

@Service
public class MenusServiceImpl extends ServiceImpl<MenusMapper, Menus> implements MenusService{

    @Override
    public List<Menus> getList() {

        QueryWrapper<Menus> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(Menus::getWeight);
        List<Menus> menusList = list(wrapper);
        return buildTree(menusList);
    }

    @Override
    @Transactional(rollbackFor = {java.lang.Exception.class})
    public boolean doEdit(Menus menus) {
        return saveOrUpdate(menus);
    }

    @Override
    public boolean checkDelete(Integer id) {
        return removeById(id);
    }

    // 构造结构
    public List<Menus> buildTree(List<Menus> menusList) {
        List<Menus> tree = new ArrayList<>();
        // 构建根节点，即父节点为null的节点
        for (Menus menu : menusList) {
            if (menu.getPid().equals(0)) {
                tree.add(buildTreeRecursive(menu, menusList));
            }
        }
        return tree;
    }

    private Menus buildTreeRecursive(Menus parentNode, List<Menus> menusList) {
        List<Menus> children = new ArrayList<>();

        for (Menus menu : menusList) {
            if (!menu.getPid().equals(0) && menu.getPid().equals(parentNode.getMenuId())) {
                // 递归构建子节点
                children.add(buildTreeRecursive(menu, menusList));
            }
        }
        parentNode.setChildren(children);
        return parentNode;
    }
}
